package com.test.springsecurity.entity;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 封装用户信息
 * 区别里面的user
 */
@Data
@Slf4j
public class AppUser implements UserDetails {
    private int id;
    private String username;
    private String password;

    private List<Role> roles;//一个用户拥有多个角色

    @Override
    /*
    *泛型上限 后面写的为这个类的子类
    * */
    /**
     * 返回当前用户的所有角色、权限信息：需要把所有的角色、权限信息封装成GrantedAuthority类对象
     */
    public Collection<? extends GrantedAuthority> getAuthorities() {

        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        /*//遍历角色、权限信息进行封装
        for(Role role :roles){
            //封装角色信息
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));

            //遍历封装权限信息
            for(Perms perms:role.getPerms()){
                grantedAuthorities.add(new SimpleGrantedAuthority(perms.getName()));
            }
        }*/
        //遍历角色、权限信息进行封装
        roles.forEach(
                role->{
                    grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
                    role.getPerms().forEach(
                            perms -> {
                                grantedAuthorities.add(new SimpleGrantedAuthority(perms.getName()));
                            }
                    );

                }
        );
        log.info("权限信息"+grantedAuthorities.toString());

        //返回
        return grantedAuthorities;
    }

    /**
     * 当前用户的账号是否过期 true 为没有过期
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 当前用户是否被否定 true没有被锁定
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 密码是否没有过期
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 当前用户是否可用
     * @return
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
